#include "ASCTOHEX.h"
#include <QString>
#include <QTextStream>
#include <QRegularExpression>

ASCTOHEX::ASCTOHEX(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);

	connect(ui.btn_ASCTOHEX, &QPushButton::clicked, this, &ASCTOHEX::on_btn_ASCTOHEX_clicked);
	connect(ui.btn_HEXTOASC, &QPushButton::clicked, this, &ASCTOHEX::on_btn_HEXTOASC_clicked);
}

QString ASCTOHEX::asciiToHex(const QString &asciiStr) {
	QString hexStr;
	for (QChar ch : asciiStr) {
		hexStr.append(QString::number(ch.unicode(), 16).toUpper() + " ");
	}
	return hexStr.trimmed();
}

QString ASCTOHEX::hexToAscii(const QString &hexStr) {
	QString asciiStr;
	QStringList hexList = hexStr.split(' ', QString::SkipEmptyParts);
	bool ok;
	for (const QString &hex : hexList) {
		QChar ch(hex.toInt(&ok, 16));
		if (ok) {
			asciiStr.append(ch);
		}
		else {
			return "输入有误";
		}
	}
	return asciiStr;
}

void ASCTOHEX::on_btn_ASCTOHEX_clicked() {
	QString asciiText = ui.textEdit_ASC->toPlainText();
	QString hexResult = asciiToHex(asciiText);
	ui.textEdit_HEX->setText(hexResult);
}

void ASCTOHEX::on_btn_HEXTOASC_clicked() {
	QString hexText = ui.textEdit_HEX->toPlainText();
	QString asciiResult = hexToAscii(hexText);
	ui.textEdit_ASC->setText(asciiResult);
}
